package org.meetunexpectedly.service.video.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.meetunexpectedly.entity.video.Type;
import org.meetunexpectedly.holder.UserHolder;
import org.meetunexpectedly.mapper.video.TypeMapper;
import org.meetunexpectedly.service.user.UserService;
import org.meetunexpectedly.service.video.TypeService;
import org.meetunexpectedly.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 分类服务实现类
 * @Author: pupil
 * @Date: 2024/08/13 下午 6:57
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public List<String> randomLabels(int num) {
        List<Type> types = this.list(null);
        Collections.shuffle(types);
        List<String> labels = new ArrayList<>();

        for (Type type : types) {
            for (String label : type.buildLabels()) {
                if (labels.size() == num) {
                    return labels;
                }
                labels.add(label);
            }
        }
        return labels;
    }

    @Override
    public List<Type> getTypes(HttpServletRequest request) {
        // 系统所有的分类
        List<Type> types = this.list(new LambdaQueryWrapper<Type>().select(Type::getIcon, Type::getId, Type::getName,Type::getOpen).orderByDesc(Type::getSort));

        // 用户订阅的分类
        Set<Long> subscribeTypes = userService.listSubscribeTypes(JwtUtils.getUserId(request))
                .stream().map(Type::getId).collect(Collectors.toSet());

        // 设置该分类用户是否订阅了
        for (Type type : types) {
            if (subscribeTypes.contains(type.getId())) {
                type.setUsed(true);
            } else {
                type.setUsed(false);
            }
        }
        return types;
    }
}
